/* 
	@license.copyright@
	@license.licenseInfo@
	$Id: JSMinTask.java 14 2007-11-11 16:28:55Z denis.riabtchik $
*/

package jgrouse.jgtools.jsmin;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Iterator;

import jgrouse.jgtools.BaseTask;

import org.apache.tools.ant.BuildException;
import org.inconspicuous.jsmin.JSMin;

public class JSMinTask extends BaseTask
{
	public JSMinTask()
	{
	}
	
	
	public void execute() throws BuildException
	{
		String output = getOutput();
		if (output == null)
		{
			throw new BuildException("Output directory not specified");
		}
		File base = getProject().getBaseDir();
		File of = new File(output);
		File outputFile = of.isAbsolute()? of : new File(base, output);		
		for (Iterator iter = getFiles().iterator(); iter.hasNext();)
		{
			FileInfo fileInfo = (FileInfo) iter.next();
			InputStream fis = null;
			OutputStream fos = null;
			try
			{
				File src = new File(fileInfo.dir, fileInfo.file);
				File out = new File(outputFile, fileInfo.file);
				out.getParentFile().mkdirs();
				File realFile = out.getAbsoluteFile().equals(src.getAbsoluteFile())? File.createTempFile("jsmin", "tmp", out.getParentFile()) : out;
				System.out.println("Processing " + src.getAbsolutePath() + " to " + out.getAbsolutePath());
				fis = new FileInputStream(src);
				fos = new FileOutputStream(realFile);
				JSMin jsmin = new JSMin(fis, fos);
				jsmin.jsmin();
				fis.close();
				fis = null;
				fos.close();
				fos = null;
				if (realFile != out)
				{
					if (out.exists())
					{
						out.delete();
					}
					realFile.renameTo(out);
				}
				
			} catch (Exception e)
			{
				throw new BuildException(e);
			}
			finally
			{
				if (fis != null)
				{
					try
					{
						fis.close();
					} catch (IOException e)
					{
					}
				}
				if (fos != null)
				{
					try
					{
						fos.close();
					} catch (IOException e)
					{
						e.printStackTrace();
					}
				}
			}
		}
	}

	
}
